package com.topisv.tms.web.ulorder;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiGoodsSku;
import com.topisv.tms.entity.EdiOrderItem;
import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.entity.LogisticsCompany;
import com.topisv.tms.entity.QueryParamHolder;
import com.topisv.tms.entity.ulorder.Ulorder;
import com.topisv.tms.entity.work.WorkTaskItem;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.EdiGoodsSkuService;
import com.topisv.tms.service.EdiOrderItemService;
import com.topisv.tms.service.LogisticsCompanyService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.ulorder.UlorderService;
import com.topisv.tms.service.work.WorkTaskItemService;
import com.topisv.tms.tools.ExcelUtils;
import com.topisv.tms.web.base.BaseDataTableController;

/**
 * 线下订单
 * @author chenhong
 *
 */
@Controller
@RequestMapping(value = "/ulorder")
public class UlorderController extends BaseDataTableController{

	private static final Logger logger = LoggerFactory.getLogger(UlorderController.class);

	@Autowired
	private CustomersService customersService;
	@Autowired
	private LogisticsCompanyService logisticsCompanyService;
	@Autowired
	private UlorderService ulorderService;
	@Autowired
	private AreaGroupService areaGroupService;
	@Autowired
	private EdiOrderItemService ediOrderItemService;
	@Autowired
	private WorkTaskItemService workTaskItemService;
	@Autowired
	private EdiGoodsSkuService ediGoodsskuService;
	/**
	 * 导向线下订单管理页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "v2_toUlorderMgrPage")
	public String toUlorderMgrPagee(Model model, ServletRequest request) {
		try {
			//查出当前用户关联的商家列表
			fillSelectValue(model, request.getParameter("_customerCode"));
		} catch (Exception e) {
			logger.error("error",e);
		}
		return "ulorder/ulorderMgr";
	}
	
	
	/**
	 * 查询
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "queryUlorder")
	public void queryUlorder(@RequestBody JSONParam[] paramJson, HttpServletRequest request,HttpServletResponse response) {
		try {
			//查出当前用户关联的商家列表
			ShiroUser curUser = getShiroUser();
			QueryParamHolder paramHolder = collectParam(paramJson,"_");
			//取消单查询结果
			Map<String, Object> param = paramHolder.getSearchParams();
			String fromDateStr=(String)param.get("fromDate");
			String toDateStr=(String) param.get("toDate");
			String customerCode=(String) param.get("customerCode");
			String warehouseCode=(String) param.get("warehouseCode");
			
			if(StringUtils.isBlank(customerCode)){
				param.put("customerCodes", this.customersService.loadCustomerByAuthority(curUser.jobuuid));
			}else{
				param.put("customerCodes", customerCode);
			}
			
			if(StringUtils.isBlank(warehouseCode)){
				param.put("areagroups", curUser.areagroups);
			}else{
				param.put("areagroups", warehouseCode);
			}
			
			Date fromDate=null;
			Date toDate=null;
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			if(StringUtils.isNotEmpty(fromDateStr)){
				fromDate=sdf.parse(fromDateStr+" 00:00:00");
			}
			if(StringUtils.isNotEmpty(toDateStr)){
				toDate=sdf.parse(toDateStr+" 23:59:59");
			}
			param.put("fromDate1", fromDate);
			param.put("toDate1", toDate);
			param.put("exceptionType", "cancel");
			
			Page<Ulorder> page = this.ulorderService.loadPageByParam(paramHolder);
			response.getWriter().print(bulidJSON(page));
		} catch (Exception e) {
			
			logger.error("error",e);
		}
	}
	
	/**
	 * 导向创建线下订单页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "toUlorderPage")
	public String toUlorderPage(Model model, ServletRequest request) {
		try {
			//查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			model.addAttribute("userType",curUser.userType);
			
			//初始页面
			model.addAttribute("tab1", "active");
			model.addAttribute("tab2", "");
			model.addAttribute("typeName", "线下订单");
			
			//快递公司
			List<LogisticsCompany> cmpList=this.logisticsCompanyService.findAll();
			model.addAttribute("cmpList",cmpList);
			
		} catch (Exception e) {
			logger.error("error",e);
		}
		return "ulorder/ulorder";
	}
	
	
	/**
	 * 创建订单
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "ajaxCreateBill")
	public void ajaxCreateBill(ServletRequest request,HttpServletResponse response) {
		
		PrintWriter out=null;
		JSONObject json=null;
		
		try {
			out = response.getWriter();
			json = new JSONObject();
			
			//获取数据
			String customerCode=request.getParameter("customerCode");
			String warehouseCode=request.getParameter("warehouseCode");
			String companyCode=request.getParameter("companyCode");
			
			String fromName=request.getParameter("fromName");
			String fromTel=request.getParameter("fromTel");
			String fromAddress=request.getParameter("fromAddress");
			
			String toName=request.getParameter("toName");
			String toTel=request.getParameter("toTel");
			String toAddress=request.getParameter("toAddress");
			
			//整理商品信息
			String jsonText=request.getParameter("jsonText");
			JSONArray infoArray = JSONArray.fromObject(jsonText);
			Map<String, Integer> infoMap=new HashMap<String, Integer>();
			for (Object info : infoArray) {
				Map<String, Object> map=(Map<String, Object>)info;
				String sku=(String)map.get("sku");
				Integer num=Integer.valueOf(map.get("num")+"");
				infoMap.put(sku, num);
			}
			
			//创建订单
			Map<String, Object> map=this.ulorderService.createBill(infoMap,customerCode,warehouseCode,companyCode,fromName,fromTel,fromAddress,toName,toTel,toAddress);
			
			json.put("msg", map.get("msg"));
			json.put("content", map.get("content"));
			out.print(json);
	    		
		} catch (Exception e) {
			
			json.put("msg", "error");
			out.print(json);
		}
	}
	
	/**
	 * @param orderno
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "toUlorderDetail/{orderno}")
	public String toUlorderDetail(@PathVariable("orderno") String orderno,HttpServletResponse response,Model model){
		try {
			//查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			
			//快递公司
			List<LogisticsCompany> cmpList=this.logisticsCompanyService.findAll();
			model.addAttribute("cmpList",cmpList);
			
			//仓库
			List<AreaGroup> warehouseList=this.areaGroupService.findAll();
			model.addAttribute("warehouseList",warehouseList);
			
			//订单信息
			Ulorder ulorder=this.ulorderService.loadByOrderno(orderno);
			model.addAttribute("ulorder",ulorder);
			
			//商品信息
			List<EdiOrderItem> goodsList=this.ediOrderItemService.findByOrdeno(ulorder.getOrderno());
			model.addAttribute("goodsList",goodsList);
			
			//初始页面
			model.addAttribute("tab1", "active");
			model.addAttribute("tab2", "");
			
		} catch (Exception e) {
			
		}
		return "ulorder/ulorder_detail";
	}
	
	/**
	 * 导向处理线下订单管理页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "v2_toUlorderHandleMgrPage")
	public String toUlorderHandleMgrPage(Model model, ServletRequest request) {
		try {
			//查出当前用户关联的商家列表
			fillSelectValue(model, request.getParameter("_customerCode"));
			//未分配的拣货任务
			model.addAttribute("_status", "login");
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return "ulorder/ulorderHandleMgr";
	}
	
	
	/**
	 * 查询
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "queryUlorderHandle")
	public void queryUlorderHandle(@RequestBody JSONParam[] paramJson, HttpServletRequest request,HttpServletResponse response) {
		try {
			//查出当前用户关联的商家列表
			ShiroUser curUser = getShiroUser();
			QueryParamHolder paramHolder = collectParam(paramJson,"_");
			//取消单查询结果
			Map<String, Object> param = paramHolder.getSearchParams();
			String fromDateStr=(String) param.get("fromDate");
			String toDateStr=(String) param.get("toDate");
			String customerCode=(String) param.get("customerCode");
			String warehouseCode=(String) param.get("warehouseCode");
			String status = (String)param.get("status");
			if(StringUtils.isBlank(customerCode)){
				param.put("customerCodes", this.customersService.loadCustomerByAuthority(curUser.jobuuid));
			}else{
				param.put("customerCodes", customerCode);
			}
			
			if(StringUtils.isBlank(warehouseCode)){
				param.put("areagroups", curUser.areagroups);
			}else{
				param.put("areagroups", warehouseCode);
			}
			
			Date fromDate=null;
			Date toDate=null;
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			if(StringUtils.isNotEmpty(fromDateStr)){
				fromDate=sdf.parse(fromDateStr+" 00:00:00");
			}
			if(StringUtils.isNotEmpty(toDateStr)){
				toDate=sdf.parse(toDateStr+" 23:59:59");
			}
			param.put("fromDate1", fromDate);
			param.put("toDate1", toDate);
			//param.put("exceptionType", "cancel");
			param.put("status", status);
			
			Page<Ulorder> page = this.ulorderService.loadPageByParam(paramHolder);
			response.getWriter().print(bulidJSON(page));
		} catch (Exception e) {
			
			logger.error("error",e);
		}
	}
	
	/**
	 * 导向处理线下单页面
	 * @param orderno
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "toHandleUlorder/{orderno}")
	public String toHandleUlorder(@PathVariable("orderno") String orderno,HttpServletResponse response,Model model){
		try {
			//查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			
			//快递公司
			List<LogisticsCompany> cmpList=this.logisticsCompanyService.findAll();
			model.addAttribute("cmpList",cmpList);
			
			//仓库
			List<AreaGroup> warehouseList=this.areaGroupService.findAll();
			model.addAttribute("warehouseList",warehouseList);
			
			//订单信息
			Ulorder ulorder=this.ulorderService.loadByOrderno(orderno);
			model.addAttribute("ulorder",ulorder);
			
			//商品信息
			List<EdiOrderItem> goodsList=this.ediOrderItemService.findByOrdeno(ulorder.getOrderno());
			model.addAttribute("goodsList",goodsList);
			
			//拣货信息
			List<WorkTaskItem> pickInfoList=this.workTaskItemService.loadByOrderno(ulorder.getOrderno());
			model.addAttribute("pickInfoList",pickInfoList);
			
			//初始页面
			model.addAttribute("tab1", "active");
			model.addAttribute("tab2", "");
			
		} catch (Exception e) {
			
		}
		return "ulorder/ulorder_handle";
	}
	
	/**
	 * 导出线下拣货单
	 * @param orderno 线下拣货单订单号
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "exportExcel/{orderno}")
	public String exportExcelByOrderNO(@PathVariable("orderno") String orderno, Model model, ServletRequest request,ServletResponse response){
		FileInputStream f=null;
		OutputStream output=null;
		try {
			
			Date now=new Date();
			DateFormat df=new SimpleDateFormat("yyyyMMddhhmmss");
			Ulorder ulorder = ulorderService.loadByOrderno(orderno);
			
			/** 定义导出数据集合 */
			List<Object[]> list = new ArrayList<Object[]>();
				
			Object[] obj = {
					ulorder.getCustomerOrdeno(),
					ulorder.getWarehouse().getGroupName(),
					ulorder.getWeight(),
					ulorder.getExpCompany(),
					ulorder.getExpNo(),
					ulorder.getFromName(),
					ulorder.getFromAddress(),
					ulorder.getFromTel(),
					ulorder.getToName(),
					ulorder.getToAddress(),
					ulorder.getToTel(),
				    null
			};
			list.add(obj);
			/** 导出数据 */
			String[] title = { "客户订单号", "发货仓库","重量","快递公司", "快递单号","寄件人姓名","寄件地址", "寄件电话","收件人姓名","收件地址","收件电话"};
			String filepath = "线下拣货单_"+ulorder.getCustomerOrdeno()+".xls";
			String title_page="线下拣货单（客户订单号："+ulorder.getCustomerOrdeno()+"）";
			ExcelUtils.writeExcel(title, filepath,title_page, df.format(now) , list); // 生成excel
			
			/** 把生成的excel文件读出字节返回给客户端 */
			((HttpServletResponse)response).setHeader("Content-disposition", "attachment; filename="+ new String(filepath.getBytes("gb2312"),"iso8859-1"));
			f = new FileInputStream(ExcelUtils.TEMPPATH+filepath);
			byte[] fb = new byte[f.available()];
			f.read(fb);
			ByteArrayInputStream bais = new ByteArrayInputStream(fb);
			output =((HttpServletResponse)response).getOutputStream();
			int by = 0;
			while ((by = bais.read()) != -1) {
				output.write(by);
			}
			output.flush();
		} catch (Exception e) {
			return "error";
		}finally{
			if (output!=null) {
				try { output.close(); } catch (IOException e) {logger.error("error",e);}
			}
			if (f!=null) {
				try { f.close(); } catch (IOException e)  {logger.error("error",e);}
			}
		}
		return null;
	}
	
	/**
	 * 发货
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxSend")
	@ResponseBody
	public String ajaxSend(ServletRequest request,HttpServletResponse response) {
		try {
			//获取数据
			String orderno=request.getParameter("orderno");
			String weight=request.getParameter("weight");
			String expressNo=request.getParameter("expressNo");
			
			//创建订单
			this.ulorderService.send(orderno,weight,expressNo);
			
			return "true";
	    		
		} catch (Exception e) {
			logger.info("发货处理异常:{}", request.getParameter("orderno"), e);
			return "false";
		}
	}
	
	
	/**
	 * 发货单确认（重发接口）
	 *
	 * @param 
	 * @return 
	 * @throws 
	 * @author yuansheng
	 * @version 1.0.0
	 */
	@RequestMapping(value = "ajaxResend")
    @ResponseBody
	public Object ajaxResend(String orderNo){
	    JSONObject json =new JSONObject();
	    try {
            String msg = ulorderService.ajaxResend(orderNo);
            json.put("msg", msg);
            return json;
        } catch (Exception e) {
            log.info("发货单确认（重发接口）:" , e);
            json.put("msg", "发送失败，请稍后再试");
            return json;
        }
	}
	
	/**
	 * 打印拣货单
	 * @param orderno
	 * @return
	 */
	@RequestMapping(value = "ajaxToPrint")
	@ResponseBody
	public Object ajaxToPrint(@RequestParam(value = "orderno") String orderno,@RequestParam(value = "customerCode") String customerCode) {
		try {
			//获取数据
			List<WorkTaskItem> pickInfoList=this.workTaskItemService.loadByOrderno(orderno);
			if(null==pickInfoList) return "error";
			for (WorkTaskItem workTaskItem : pickInfoList) {
				if(StringUtils.isBlank(workTaskItem.getSkuName())){//当SKU的品名为空时,重新赋值
					EdiGoodsSku ediGoodsSku= this.ediGoodsskuService.findBySkuAndCustomerCode(workTaskItem.getSku(),customerCode);
					workTaskItem.setSkuName(null==ediGoodsSku?"":ediGoodsSku.getSkuName());
				}
			}
			return pickInfoList;
	    		
		} catch (Exception e) {
			log.error("查询任务异常", e);
			return "error";
		}
	}
}
